﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CarInfor.DAL;
using CarInfor.BLL;

namespace CarInfor.UI
{
    public partial class frmCarInfor : Form
    {
        YearCheck yearCheck = new YearCheck();
        private ActionType curActionType;
        private string key;
        public frmCarInfor(ActionType type, string id)
        {
            InitializeComponent();
            curActionType = type;
            key = id;
            Init();
            if (curActionType == ActionType.New)
            {
                this.Text = "年检信息--新建";

            }
            else if (curActionType == ActionType.Edit)
            {
                this.Text = "年检信息--编辑";
                yearCheck.QueryWithKey(key);
                BindText(yearCheck);
            }
            this.txtCarNumber.Validating += new CancelEventHandler(txtCarNumber_Validating);
        }

        /// <summary>
        /// 车牌号验证
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void txtCarNumber_Validating(object sender, CancelEventArgs e)
        {
            if (curActionType == ActionType.New)
            {
                if (!string.IsNullOrEmpty(this.txtCarNumber.Text.Trim()) && this.cboCarType.SelectedIndex != 0)
                {
                    string sql = " CarNumber='" + this.txtCarNumber.Text.Trim() + "' and CarType='" + this.cboCarType.SelectedItem.ToString() + "'";
                    YearCheck yc = new YearCheck();
                    if (yc.Query(sql).Rows.Count > 0)
                    {
                        if (MessageHelper.ShowYesNoChoice("检测到车牌号（" + this.txtCarNumber.Text.Trim() + this.cboCarType.SelectedItem.ToString() + "）已经存在，是否进入编辑模式？") == DialogResult.Yes)
                        {
                            key = yc.Query(sql).Rows[0]["编号"].ToString();
                            curActionType = ActionType.Edit;
                            this.Text = "年检信息--编辑";
                            yearCheck.QueryWithKey(key);
                            BindText(yearCheck);
                        }
                        else
                        {
                            e.Cancel = true;
                        }
                    }
                }
            }
        }

        private void BindCarType()
        {

            this.cboCarType.Items.Clear();
            CarType carType = new CarType();
            DataTable dt = carType.Query();
            this.cboCarType.Items.Add("--请选择--");
            foreach (DataRow row in dt.Rows)
            {
                this.cboCarType.Items.Add(row["类型名称"].ToString());
            }
            this.cboCarType.SelectedIndex = 0;

        }
        private void Init()
        {
            this.txtCarNumber.SelectionStart = this.txtCarNumber.Text.Length;
            this.dtpCheckDate.Value = DateTime.Now;
            DateTime startDT = Common.GetDateNextYearEndDay(this.dtpCheckDate.Value);
            this.dtpExpireDate.Value = startDT;
            this.dtpBaoHuDate.Value = DateTime.Now;
            BindCarType();
        }

        void BindText(YearCheck yc)
        {

            this.txtCarNumber.Text = yc.CarNumber;
            this.cboCarType.SelectedItem = yc.CarType;
            this.txtOnwerName.Text = yc.OwnerName;
            this.txtTel.Text = yc.Telephone;
            this.dtpCheckDate.Text = yc.CheckDate;
            this.dtpExpireDate.Text = yc.ExpireDate;
            this.dtpBaoHuDate.Text = yearCheck.BaoHuDate;
            this.txtMemo.Text = yc.Memo;
            this.txtCarNumber.Focus();
            this.txtCarNumber.SelectionStart = this.txtCarNumber.Text.Length;
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                if (!VerifyBeforeSave())
                {
                    return;
                }

                //检查是否已经报废
                YearCheck yc = new YearCheck();
                yc.CarType = this.cboCarType.SelectedItem == null ? string.Empty : this.cboCarType.SelectedItem.ToString();
                yc.BaoHuDate = this.dtpBaoHuDate.Value.ToShortDateString();
                if (YearCheckSplit.GetYearSplit(yc) < 0)
                {
                    if (DialogResult.No == MessageHelper.ShowYesNoChoice("该车辆已经到报废时间,不能再年检！是否保存？"))
                    {
                        return;
                    }
                }

                if (curActionType == ActionType.New)
                {

                    YearCheck newObj = new YearCheck();
                    newObj.ID = Guid.NewGuid().ToString();
                    newObj.CarNumber = this.txtCarNumber.Text.Trim();
                    newObj.CarType = this.cboCarType.SelectedItem.ToString().Equals("--请选择--") ? string.Empty : this.cboCarType.SelectedItem.ToString();
                    newObj.OwnerName = this.txtOnwerName.Text.Trim();
                    newObj.Telephone = this.txtTel.Text;
                    newObj.CheckDate = this.dtpCheckDate.Text.Trim();
                    newObj.ExpireDate = this.dtpExpireDate.Text.Trim();
                    newObj.BaoHuDate = this.dtpBaoHuDate.Text.Trim();
                    newObj.Memo = this.txtMemo.Text.Trim();
                    newObj.Insert();
                    this.DialogResult = DialogResult.OK;
                }
                else if (curActionType == ActionType.Edit)
                {

                    yearCheck.CarNumber = this.txtCarNumber.Text.Trim();
                    yearCheck.CarType = this.cboCarType.SelectedItem.ToString().Equals("--请选择--") ? string.Empty : this.cboCarType.SelectedItem.ToString();
                    yearCheck.OwnerName = this.txtOnwerName.Text.Trim();
                    yearCheck.Telephone = this.txtTel.Text;
                    yearCheck.CheckDate = this.dtpCheckDate.Text.Trim();
                    yearCheck.ExpireDate = this.dtpExpireDate.Text.Trim();
                    yearCheck.BaoHuDate = this.dtpBaoHuDate.Text.Trim();
                    yearCheck.Memo = this.txtMemo.Text.Trim();
                    yearCheck.UpdateWithKey(key);
                    this.DialogResult = DialogResult.OK;
                }
            }
            catch (Exception ex)
            {
                MessageHelper.ShowFail("修改失败！" + ex.Message);
                this.DialogResult = DialogResult.Cancel;
            }
        }

        /// <summary>
        /// 保存验证
        /// </summary>
        /// <returns></returns>
        bool VerifyBeforeSave()
        {
            if (string.IsNullOrEmpty(this.txtCarNumber.Text.Trim()) || this.txtCarNumber.Text.Trim() == "陕C")
            {
                MessageHelper.ShowInfo("请输入车辆号牌！");
                this.txtCarNumber.Focus();
                this.txtCarNumber.SelectionStart = this.txtCarNumber.Text.Length;
                return false;
            }

            if (this.cboCarType.SelectedIndex == 0)
            {
                MessageHelper.ShowInfo("请选择车辆类型！");
                return false;
            }

            if (string.IsNullOrEmpty(this.txtOnwerName.Text.Trim()))
            {
                MessageHelper.ShowInfo("请输入车主姓名！");
                this.txtOnwerName.Focus();
                return false;
            }

            if (string.IsNullOrEmpty(this.txtTel.Text.Trim()))
            {
                MessageHelper.ShowInfo("请输入联系电话！");
                this.txtTel.Focus();
                return false;
            }

            if (curActionType == ActionType.Edit)
            {
                YearCheck newObj = new YearCheck();
                DataTable dt = newObj.Query(" CarNumber='" + this.txtCarNumber.Text.Trim() + "' and  CarType='" + this.cboCarType.SelectedItem.ToString() + "' and ID<>'" + key + "'");
                if (dt.Rows.Count > 0)
                {
                    MessageHelper.ShowInfo("车牌号(" + this.txtCarNumber.Text.Trim() + this.cboCarType.SelectedItem.ToString() + ")已经存在！");
                    return false;
                }
            }

            return true;
        }

        private void btnCancle_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        }

        /// <summary>
        /// 车辆类型验证
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cboCarType_Validating(object sender, CancelEventArgs e)
        {
            if (curActionType == ActionType.New)
            {
                if (!string.IsNullOrEmpty(this.txtCarNumber.Text.Trim()) && this.cboCarType.SelectedIndex != 0)
                {
                    string sql = " CarNumber='" + this.txtCarNumber.Text.Trim() + "' and CarType='" + this.cboCarType.SelectedItem.ToString() + "'";
                    YearCheck yc = new YearCheck();
                    if (yc.Query(sql).Rows.Count > 0)
                    {
                        if (MessageHelper.ShowYesNoChoice("检测到车牌号（" + this.txtCarNumber.Text.Trim() + this.cboCarType.SelectedItem.ToString() + "）已经存在，是否进入编辑模式？") == DialogResult.Yes)
                        {
                            key = yc.Query(sql).Rows[0]["编号"].ToString();
                            curActionType = ActionType.Edit;
                            this.Text = "年检信息--编辑";
                            yearCheck.QueryWithKey(key);
                            BindText(yearCheck);
                        }
                        else
                        {
                            e.Cancel = true;
                        }
                    }
                }
            }
        }

        /// <summary>
        /// 开始日期变化时，改变结束日日
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dtpCheckDate_ValueChanged(object sender, EventArgs e)
        {
            //DateTime startDT = Common.GetDateNextYearEndDay(this.dtpCheckDate.Value);

            YearCheck yc = new YearCheck();
            yc.CarType = this.cboCarType.SelectedItem == null ? string.Empty : this.cboCarType.SelectedItem.ToString();
            yc.BaoHuDate = this.dtpBaoHuDate.Value.ToShortDateString();
            //this.dtpExpireDate.Value = startDT;
            int sp = YearCheckSplit.GetYearSplit(yc);
            if (sp > 0)
            {
                this.dtpExpireDate.Value = this.dtpCheckDate.Value.AddMonths(sp);
            }
            else
            {
                this.dtpExpireDate.Value = Convert.ToDateTime("8888-8-8 12:00:00");
            }

        }

        /// <summary>
        /// 保护日期变化时，改变结束日日
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dtpBaoHuDate_ValueChanged(object sender, EventArgs e)
        {
            YearCheck yc = new YearCheck();
            yc.BaoHuDate = this.dtpBaoHuDate.Value.ToShortDateString();
            yc.CarType = this.cboCarType.SelectedItem == null ? string.Empty : this.cboCarType.SelectedItem.ToString();
            int sp = YearCheckSplit.GetYearSplit(yc);
            if (sp > 0)
            {
                this.dtpExpireDate.Value = this.dtpCheckDate.Value.AddMonths(sp);
            }
            else
            {
                this.dtpExpireDate.Value = Convert.ToDateTime("8888-8-8 12:00:00");
            }
        }
    }
}
